const ACCOUNT = "18040585033";
const PASSWORD = "q461309827";
const QQ = "3024412629";
const PACKAGE_ID_QQ = "com.tencent.mobileqq";               // QQ
const PACKAGE_ID_DD = "com.alibaba.android.rimet";          // 钉钉
const PACKAGE_ID_TASKER = "net.dinglisch.android.taskerm";  // Tasker

// 执行时的屏幕亮度(0-255), 需要"修改系统设置"权限
const SCREEN_BRIGHTNESS = 20;

// PackageId白名单
const PACKAGE_ID_WHITE_LIST = [PACKAGE_ID_QQ, PACKAGE_ID_DD, PACKAGE_ID_TASKER];

// 公司的钉钉CorpId, 如果只加入了一家公司, 可以不填
const CORP_ID = "";

const WEEK_DAY = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

// 检查无障碍权限
auto.waitFor();

// 监听本机通知
events.observeNotification()
events.on("notification", function (n) { notificationHandler(n); });

/**
 * 打卡流程
 */
function doClock() {
  console.log("本地时间: " + getCurrentDate() + " " + getCurrentTime());
  console.log("开始打卡流程");

  brightScreen();
  unlockScreen();
  signIn();
  fastClock();

  sleep(1000);
  shutdownDingtalk();
  sleep(1000);
  lockScreen();
}

/**
 * 查询打卡
 */
function doCheckClock() {
  console.log("本地时间: " + getCurrentDate() + " " + getCurrentTime());
  console.log("开始查询打卡流程");

  brightScreen();
  unlockScreen();
  signIn();
  attendKaoqin();
  checkClockState();

  sleep(1000);
  shutdownDingtalk();
  sleep(1000);
  lockScreen();
}

/**
 * 唤醒屏幕
 */
function brightScreen() {
  console.log("唤醒设备");
  device.wakeUpIfNeeded(); // 唤醒设备
  device.keepScreenOn(); // 保持屏幕常亮
  device.setBrightnessMode(0); // 手动亮度模式
  device.setBrightness(SCREEN_BRIGHTNESS); // 屏幕亮度
  sleep(1000);

  if (!device.isScreenOn()) {
    console.warn("设备未唤醒, 重试");
    device.wakeUpIfNeeded();
    brightScreen();
  }
  else {
    console.info("设备已唤醒");
  }
  sleep(1000);
}

/**
 * 解锁屏幕
*/
function unlockScreen() {
  console.log("解锁屏幕");

  if (isDeviceLocked()) {
    swipe(500, 2000, 500, 1000, 220);

    sleep(1000);
    home();
    sleep(1000);
  }

  if (isDeviceLocked()) {
    console.error("上滑解锁失败");
    return;
  }
  console.info("屏幕已解锁");
}

/**
 * 锁屏
 */
function lockScreen() {
  console.log("关闭屏幕");

  device.cancelKeepingAwake(); // 取消屏幕常亮
  device.setBrightnessMode(1); // 自动亮度模式

  // 点击下拉栏锁屏按钮
  //swipe(950, 50, 500, 1200, 1000);
  gesture(1000, [950, 50], [500, 1600]);
  sleep(2000);
  click(920, 450);
}

function openDingtalk() {
  if (currentPackage() == PACKAGE_ID_DD) {
    console.log("已经在" + app.getAppName(PACKAGE_ID_DD) + "里");
    return;
  }
  app.launchPackage(PACKAGE_ID_DD);
  console.log("正在启动" + app.getAppName(PACKAGE_ID_DD) + "...");
  sleep(5000);
}

function shutdownDingtalk() {
  app.openAppSetting(PACKAGE_ID_DD);
  text("钉钉").waitFor();
  const closeButton = textContains("结束").findOne(); // 结束运行按钮
  if (closeButton.enabled()) {
    click("结束");
    textContains("确定").findOne();
    click("确定");
    console.log("钉钉已被关闭");
    home();
  } else {
    console.log("钉钉未能被正常关闭或不在后台运行");
    home();
  }
  sleep(1000);
}

/**
 * 启动并登陆钉钉
 */
function signIn() {
  setVolume(0); // 设备静音
  openDingtalk();

  if (currentPackage() == PACKAGE_ID_DD) {

    sleep(10000);
    if (currentActivity() == "com.alibaba.android.user.login.SignUpWithPwdActivity") {
      console.info("账号未登录");

      const account = id("et_phone_input").findOne();
      account.setText(ACCOUNT);
      console.log("输入账号");

      const password = id("et_password").findOne();
      password.setText(PASSWORD);
      console.log("输入密码");

      const privacy = id("cb_privacy").findOne();
      privacy.click();
      console.log("同意隐私协议");

      const btn_login = id("btn_next").findOne();
      btn_login.click();
      console.log("正在登陆...");
      sleep(3000);
    } else {
      console.info("账号已登录");
      sleep(1000);
    }
  }
}

/**
 * 急速打卡
 */
function fastClock() {
  let message = "";

  console.log("等待10秒的极速打卡");
  const result = textContains("打卡成功").findOnce(10000);
  if (!!result) {
    message = "极速打卡成功";
    console.log("极速打卡成功");
  } else {
    message = "未检测到极速打卡通知";
    console.log("未检测到极速打卡通知");
  }
  sendQQMessage(message);
}

/**
 * 使用 URL Scheme 进入考勤界面
 */
function attendKaoqin() {
  const url_scheme = "dingtalk://dingtalkclient/page/link?url=https://attend.dingtalk.com/attend/index.html";
  if (CORP_ID != "") {
    url_scheme = url_scheme + "?corpId=" + CORP_ID;
  }

  const activity = app.intent({
    action: "VIEW",
    data: url_scheme,
    //flags: [Intent.FLAG_ACTIVITY_NEW_TASK]
  });
  app.startActivity(activity);
  console.log("正在进入考勤界面...");

  textContains("申请").waitFor();
  console.info("已进入考勤界面");
  sleep(5000);
}

/**
 * 查询打卡状态
 */
function checkClockState() {
  let message = "";

  const KEY_CLOCK_IN = /上班(\d+:\d+)/;
  if (textMatches(KEY_CLOCK_IN).exists()) {
    sleep(500);
    let widgets = textMatches(KEY_CLOCK_IN).find();
    for (let index = 0; index < widgets.length; index++) {
      let widget = widgets[index];
      let sub1 = widget.parent().child(1).child(0).child(0);
      //let sub2 = widget.parent().child(1).child(0).child(1);
      if (sub1.text() == "未打卡") {
        message += "上班 " + sub1.text() + "\n";
      } else {
        let sub2 = widget.parent().child(1).child(0).child(1);
        message += "上班 " + sub2.text() + "\n";
      }
    }
  }

  const KEY_CLOCK_OUT = /下班(\d+:\d+)/;
  if (textMatches(KEY_CLOCK_OUT).exists()) {
    sleep(500);
    let widgets = textMatches(KEY_CLOCK_OUT).find();
    for (let index = 0; index < widgets.length; index++) {
      let widget = widgets[index];
      let sub1 = widget.parent().child(1).child(0).child(0);
      //let sub2 = widget.parent().child(1).child(0).child(1);
      if (sub1.text() == "未打卡") {
        message += "下班 " + sub1.text();
      } else {
        let sub2 = widget.parent().child(1).child(0).child(1);
        message += "下班 " + sub2.text();
      }
    }
  }

  sendQQMessage(message);
}

function notificationHandler(n) {
  const packageId = n.getPackageName();   // 获取通知包名
  const abstract = n.tickerText;          // 获取通知摘要
  const text = n.getText();               // 获取通知文本

  // 过滤 PackageId 白名单之外的应用所发出的通知
  if (!filterNotification(packageId, abstract, text)) {
    return;
  }

  // 监听摘要为"定时打卡"的通知,不一定要从Tasker中发出通知,日历/定时器等App均可实现
  if (abstract == "定时打卡" && !suspend) {
    needWaiting = true;
    threads.shutDownAll();
    threads.start(function () { doClock(); });
    return;
  }

  sleep(1000);
  switch (text) {
    case "打卡":
      needWaiting = false;
      threads.shutDownAll();
      threads.start(function () { doClock(); });
      break;
    case "查询":
      threads.shutDownAll();
      threads.start(function () { doCheckClock(); });
      break;
    case "锁屏": sleep(10000); lockScreen(); break;
    case "解锁": brightScreen(); unlockScreen(); break;
    default: break;
  }
}

/**
 * 发送QQ消息
 * @param {string} message 消息内容
 */
function sendQQMessage(message) {
  console.log("发送QQ消息");

  app.startActivity({
    action: "android.intent.action.VIEW",
    data: "mqq://im/chat?chat_type=wpa&version=1&src_type=web&uin=" + QQ,
    packageName: "com.tencent.mobileqq",
  });

  // waitForActivity("com.tencent.mobileqq.activity.SplashActivity")

  id("input").findOne().setText(message);
  id("fun_btn").findOne().click();

  sleep(1000);
  home();
  sleep(1000);
}

/**
 * 通知过滤器,只处理白名单内的应用的通知
 * @param {string} packageId 通知包名
 * @param {string} abstract 通知摘要
 * @param {string} text 通知文本
 * @returns
 */
function filterNotification(packageId, abstract, text) {
  const check = PACKAGE_ID_WHITE_LIST.some(function (item) { return packageId == item });
  if (check) {
    console.verbose("┌─────────────────────────────────────┐");
    console.verbose("│ 通知包名: " + packageId);
    console.verbose("│ 通知摘要: " + abstract);
    console.verbose("│ 通知文本: " + text);
    console.verbose("└─────────────────────────────────────┘");
  }
  return check;
}

function dateDigitToString(num) {
  //return num < 10 ? '0' + num : num;
  return num.toString().padStart(2, '0');
}

function getCurrentTime() {
  const currentDate = new Date();
  const hours = dateDigitToString(currentDate.getHours());
  const minute = dateDigitToString(currentDate.getMinutes());
  const second = dateDigitToString(currentDate.getSeconds());
  const formattedTimeString = hours + ':' + minute + ':' + second;
  return formattedTimeString;
}

function getCurrentDate() {
  const currentDate = new Date();
  const year = dateDigitToString(currentDate.getFullYear());
  const month = dateDigitToString(currentDate.getMonth() + 1);
  const date = dateDigitToString(currentDate.getDate());
  const week = currentDate.getDay();
  const formattedDateString = year + '-' + month + '-' + date + '-' + WEEK_DAY[week];
  return formattedDateString;
}

// 屏幕是否为锁定状态
function isDeviceLocked() {
  importClass(android.app.KeyguardManager);
  importClass(android.content.Context);
  const km = context.getSystemService(Context.KEYGUARD_SERVICE);
  return km.isKeyguardLocked();
}

// 设置媒体和通知音量
function setVolume(volume) {
  device.setMusicVolume(volume);
  device.setNotificationVolume(volume);
  console.verbose("媒体音量:" + device.getMusicVolume());
  console.verbose("通知音量:" + device.getNotificationVolume());
}
